﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

#if UNITY_EDITOR
using UnityEditor;
#endif

[AddComponentMenu("PUEX/Emitter/CircleEmitter")]
public class PUEXCircleEmitter : PUEXEmitter {

	#region - Editable property
	[Header("CircleEmitter:")]
	public float radius;
	public bool emitOnSurface;
	public bool emitLinear;
	public bool alignDirection;
	public bool tangentDirection;
	public float randomDeviant;
	public bool flipDirection;
	#endregion

	#region - Property
	protected Vector3 _emitOffset;
	#endregion
	
	#region - Lifecycle
	public PUEXCircleEmitter ()
	{
		radius = 20f;
		emitOnSurface = false;
		emitLinear = false;
		alignDirection = true;
		tangentDirection = false;
		flipDirection = false;
		randomDeviant = 0f;
	}
	#endregion

	#region - Emit
	protected override void initParticlePosition (PUEXParticle particle, int index, int requested)
	{
		float r = radius;
		if (emitOnSurface == false)
			r = Random.value * radius;

		if (emitLinear) {
			float a = timeFraction * -Mathf.PI * 2f;
			float x = Mathf.Cos (a) * r;
			float y = Mathf.Sin (a) * r;
			_emitOffset = new Vector3(x, y, 0f);
		} else {
			Vector2 v2 = Random.insideUnitCircle.normalized * r;
			_emitOffset = new Vector3(v2.x, v2.y, 0f);
		}

		particle.position = particle.originalPosition = emitterToSimulationTransform.MultiplyPoint (_emitOffset);
	}
	
	protected override void initParticleVelocity (PUEXParticle particle, int index, int requested)
	{
		if (alignDirection) {
			Vector3 dir = _emitOffset;

			if (tangentDirection) {
				dir = Vector3.Cross (dir, Vector3.forward);
			}

			if (randomDeviant > 0f) {
				dir = PUEXUtils.randomDeviant(dir, randomDeviant);
			}

			if (flipDirection) {
				dir *= -1f;
			}
			
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (dir).normalized;
		} else {
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (Random.insideUnitSphere).normalized;
		}
		
		particle.speed = particle.originalSpeed = startSpeed.getValue (timeFraction);
	}
	#endregion
	
	#region - Draw
	public void OnDrawGizmos()
	{
		if (!enabled)
			return;
		
		#if UNITY_EDITOR
		Matrix4x4 defaultMatrix = Handles.matrix;
		Handles.matrix = transform.localToWorldMatrix;

		Color defaultColor = Handles.color;
		Handles.color = Color.blue;

		Handles.DrawWireDisc(Vector3.zero, Vector3.forward, radius);

		Handles.color = defaultColor;
		Handles.matrix = defaultMatrix;
		#endif
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData systemData)
	{
		JsonData ret = base.save (systemData);

		ret ["radius"] = radius;
		ret ["emit_on_surface"] = emitOnSurface;
		ret ["emit_linear"] = emitLinear;
		ret ["align_direction"] = alignDirection;
		ret ["tangent_direction"] = tangentDirection;
		ret ["random_deviant"] = randomDeviant;
		ret ["flip_direction"] = flipDirection;
		
		return ret;
	}
	#endregion

}
